绕过linux command中密码验证

  • 脚本中碰到了批量scp的情况,并且是windows到linux的
  • 类似需要在bash中进行批量执行的,且需要验证的,如scp,或者在目标机器上远程方式执行xxx命令

思路

sshpass

  • cover了需要验证用户密码的情况,如

    sshpass -p inspur scp -r -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no /root/liruifeng/debug-publish-center.sh root@100.2.22.234:/root/

ssh-key

  • 配置ssh-key后,认证通过key验证方式进行
  • 缺点是系统重装后,节点下的figureprint会变,之前的ssh-key也会被删除
    • 本机的~/.ssh/known_hosts
    • 目标机器的~/.ssh/authorized_keys

      demo

生成本地rsa key

#生成密钥
$ ssh-keygen.exe -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa):
/c/Users/Administrator/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/Administrator/.ssh/id_rsa.
Your public key has been saved in /c/Users/Administrator/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:fVklWZFONaOM//xnDz7JK5Z+wa1PCPuV7dKZBLH40UU Administrator@USER-20151120AI
The key's randomart image is:
+---[RSA 2048]----+
|              .BE|
|            o.o=+|
|           ..oB .|
|         . ..* o |
|        S . =oo. |
|           . +=o+|
|            .o+O*|
|            +oBB=|
|           o.o+*B|
+----[SHA256]-----+

ssh-copy-id配置命令

$ ssh-copy-id -i ~/.ssh/id-rsa.pub root@100.2.22.202
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@100.2.22.202's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@100.2.22.202'"
and check to make sure that only the key(s) you wanted were added.

测试是否成功(如下,则登陆成功)

$ ssh root@100.2.22.202
Last login: Tue Aug  9 09:47:59 2016 from 100.2.22.225
[root@icenter-49374-82786 ~]#

注意点

  • 如果本地配置了~/.ssh/config,则需要配置上,免密登录才会生效
    • 且要注意,配置~/.ssh/config需要在配置ssh-copy-id之后
  • 手动配置

参考资料